package com.toman.ui.work.management;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Enum.BaseEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.BeltlineInspectEntity;
import com.toman.R;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.CustomPopWindow;
import com.toman.widget.SpaceItemDecoration;
import com.toman.widget.callback.StringLoadingCallback;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;
import okhttp3.Response;

public class BeltlineInspectActivity extends ToolBarActivity {
    CommonAdapter<BeltlineInspectEntity> adapter;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    @BindView(R.id.view)
    View view;

    private String runStatus;
    private String onlineStatus;
    private List<BeltlineInspectEntity> list = new ArrayList<>();

    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    private CustomPopWindow mCustomPopWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_beltline_inspect);
        ButterKnife.bind(this);
        initToolBar(BaseEnum.BELTLINEINSPECT.name);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();

//        }
        customer(1, 1, "");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_select, menu);
//        MenuItem menuItem = menu.findItem(R.id.menu_scan);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_select:
                        showPopMenu(view);
                        break;
                }
                return false;
            }
        });

        return true;
    }

    private void initView() {
//        ViewUtil.permission(getApplicationContext(),BaseEnum.FIRSTINSPECTION.has(PermEnum.CHECK),rlMuti);
        initAdapter();

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<BeltlineInspectEntity> beanlist = adapter.getDatas();
                BeltlineInspectEntity bean = beanlist.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", bean);
                DialogUtils.showDialog(BeltlineInspectActivity.this, "问题反馈", "获取wifi强度",
                        (dialog, which) -> IntentUtils.startActivity(BeltlineInspectActivity.this, BeltlineInspectAddActivity.class, bundle), (dialog, which) -> {
                            if (StringUtils.isEmpty(bean.getTerminalId())) {
ToastUtil.error(getApplicationContext(),"未绑定智能终端,无法获取信息强度！");
                            } else {
                                wifi(bean.getTerminalId());
                            }
                        });
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        lv.setAdapter(adapter);
        GridLayoutManager mgr = new GridLayoutManager(this, 3);
        lv.setLayoutManager(mgr);
        lv.addItemDecoration(new SpaceItemDecoration(20, 3));
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //getHttp(1,1);
//                content1=content2=content3=content4=null;
                page = 2;
                customer(1, 1, "");
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                customer(page, 2, "");
                page += 1;

            }
        });

    }

    private void initAdapter() {
        adapter = new CommonAdapter<BeltlineInspectEntity>(this, R.layout.item_beltline_card, list) {
            @Override
            protected void convert(ViewHolder holder, BeltlineInspectEntity item, final int position) {
                CardView cv = holder.getView(R.id.cv);
                holder.setText(R.id.tv_terminal_num, item.getTerminalNum());
                holder.setText(R.id.tv_beltline, item.getBeltlineName());
                holder.setText(R.id.tv_output, item.getTodayOutput() + "");
                ImageView iv_status = holder.getView(R.id.iv_status);
                ImageView iv_wifi = holder.getView(R.id.iv_wifi);
                try {
                    if (item.getTerminalStatus() == 1) {
                        iv_status.setImageResource(R.mipmap.cxxj_icon_online);
                    } else {
                        iv_status.setImageResource(R.mipmap.cxxj_icon_offline);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                switch (item.getRunStatus()) {
                    case "2":
                        cv.setCardBackgroundColor(getResources().getColor(R.color.beltline_green));
//获取资源文件
                        int resID[] = new int[]{R.mipmap.cxxj_icon_wifi_green0, R.mipmap.cxxj_icon_wifi_green1, R.mipmap.cxxj_icon_wifi_green2, R.mipmap.cxxj_icon_wifi_green3, R.mipmap.cxxj_icon_wifi};
//                        int resID = getResources().getIdentifier("cxxj_icon_wifi_blue"+"1", "mipmap", getApplicationInfo().packageName);
                        iv_wifi.setImageResource(resID[item.getTerminalSignalIntensity()]);

                        break;
                    case "1":
                        int resID2[] = new int[]{R.mipmap.cxxj_icon_wifi_yellow0, R.mipmap.cxxj_icon_wifi_yellow1, R.mipmap.cxxj_icon_wifi_yellow2, R.mipmap.cxxj_icon_wifi_yellow3, R.mipmap.cxxj_icon_wifi};
//                        int resID = getResources().getIdentifier("cxxj_icon_wifi_blue"+"1", "mipmap", getApplicationInfo().packageName);
                        iv_wifi.setImageResource(resID2[item.getTerminalSignalIntensity()]);
                        cv.setCardBackgroundColor(getResources().getColor(R.color.beltline_yellow));
                        break;
                    case "3":
                        int resID3[] = new int[]{R.mipmap.cxxj_icon_blue0, R.mipmap.cxxj_icon_wifi_blue1, R.mipmap.cxxj_icon_wifi_blue2, R.mipmap.cxxj_icon_wifi_blue3, R.mipmap.cxxj_icon_wifi};
                        iv_wifi.setImageResource(resID3[item.getTerminalSignalIntensity()]);
                        cv.setCardBackgroundColor(getResources().getColor(R.color.beltline_blue));
                        break;
                    case "0":
                        int resID4[] = new int[]{R.mipmap.cxxj_icon_wifi_gray0, R.mipmap.cxxj_icon_wifi_gray1, R.mipmap.cxxj_icon_wifi_gray2, R.mipmap.cxxj_icon_wifi_gray3, R.mipmap.cxxj_icon_wifi};
                        iv_wifi.setImageResource(resID4[item.getTerminalSignalIntensity()]);
                        cv.setCardBackgroundColor(getResources().getColor(R.color.beltline_gray));
                        break;
                        default:
                            int resID5[] = new int[]{R.mipmap.cxxj_icon_wifi_gray0, R.mipmap.cxxj_icon_wifi_gray1, R.mipmap.cxxj_icon_wifi_gray2, R.mipmap.cxxj_icon_wifi_gray3, R.mipmap.cxxj_icon_wifi};
                            iv_wifi.setImageResource(resID5[item.getTerminalSignalIntensity()]);
                            cv.setCardBackgroundColor(getResources().getColor(R.color.beltline_gray));
                            break;
                }

            }
        };
    }

    private void showPopMenu(View button) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu_select, null);
        //处理popWindow 显示内容
//        View view = contentView.findViewById(R.id.menu3);
//        ViewUtil.permission(getApplicationContext(), BaseEnum.DISPATCHING.has(PermEnum.DELETE), view);

        handleLogic(contentView);
        //创建并显示popWindow
        if (mCustomPopWindow == null) {

            mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(contentView)
                    .create()
                    .showAsDropDown(button, 0, 20);
//            mCustomPopWindow.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
//                @Override
//                public void onDismiss() {
//                    WindowManager.LayoutParams lp = getWindow().getAttributes();
//                    lp.alpha = 1f;
//                    getWindow().setAttributes(lp);
//                }
//            });

        } else {

            mCustomPopWindow.showAsDropDown(button, 0, 20);
        }

    }

    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (mCustomPopWindow != null) {
//                    mCustomPopWindow.dissmiss();
//                }
                switch (v.getId()) {
                    case R.id.rb_online:
                        onlineStatus = "0";
                        customer(1, 1, "");
                        break;
                    case R.id.rb_offline:
                        onlineStatus = "1";
                        customer(1, 1, "");
                        break;
                    case R.id.rb_0:
                        runStatus = "2";
                        customer(1, 1, "");
                        break;
                    case R.id.rb_1:
                        runStatus = "3";
                        customer(1, 1, "");
                        break;
                    case R.id.rb_2:
                        runStatus = "1";
                        customer(1, 1, "");
                        break;
                    case R.id.rb_3:
                        runStatus = "0";
                        customer(1, 1, "");
                        break;
                }

            }
        };
        contentView.findViewById(R.id.rb_online).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_offline).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_0).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_1).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_2).setOnClickListener(listener);
        contentView.findViewById(R.id.rb_3).setOnClickListener(listener);
    }


    public void customer(Integer page, final Integer type, String search) {
        if (dialog != null) {
            dialog.dismiss();
        }
        OkHttpUtils
                .get(NewBaseUrl.management_beltlineinspect_list)
                .headers("token", token)
                .params("companyId", companyId)
                .params("key", search)
                .params("limit", "28")
                .params("page", page.toString())
                .params("onlineStatus", onlineStatus)
                .params("runStatus", runStatus)

                .execute(new StringLoadingCallback(this,mPullToRefreshScrollView,search) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "调表中心: " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            ToastUtil.print("数据：" + jsonObj.getString("data"));
                            JSONObject Jpage = jsonObj.getJSONObject("page");

                            List<BeltlineInspectEntity> jsonArray = new ArrayList<BeltlineInspectEntity>(JsonExcludeNull.parseArrayExcludeNull(Jpage.getString("list"), BeltlineInspectEntity.class));
                            list.addAll(jsonArray);


                            if (list.size() == 0) {
                                mMangeNodata.setVisibility(View.VISIBLE);
                            } else {
                                mMangeNodata.setVisibility(View.GONE);
                            }
                            adapter.notifyDataSetChanged();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                        mPullToRefreshScrollView.onRefreshComplete();
                    }
                });
    }
    public void wifi(String ids) {
        if (dialog != null) {
            dialog.dismiss();
        }
        OkHttpUtils
                .get(NewBaseUrl.management_beltlineinspect_wifi)
                .headers("token", token)
                .params("terminalIds", ids)


                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "获取wifi: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
//                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            ToastUtil.makeText(getApplicationContext(),"获取wifi信号强度成功，状态约30s后会更新");


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }
}